package com.neoCalf.neoUser.config;

import com.neoCalf.neoCommon.redis.RedisComponent;
import com.neoCalf.neoCommon.redis.RedisTool;
import com.neoCalf.neoCommon.utils.CodeUtils;
import com.neoCalf.neoCommon.utils.JwtUtil;
import com.neoCalf.neoCommon.utils.SendUtils;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;


/**
 * @author 小牛
 * @version 1.0
 * @description TODO
 * @date 2025/4/9 11:34
 */
@Configuration
@Slf4j
public class CommonConfig<V> {
    @Value("${spring.redis.host}")
    private String redisLocal;
    @Value("${spring.redis.port}")
    private int redisPort;

    @Bean
    public CodeUtils codeUtils(RedisTool<String> redisTool) {
        return new CodeUtils(redisTool);
    }

    @Bean
    public RedisTool<V> redisTool(RedisTemplate<String, V> redisTemplate) {
        return new RedisTool<>(redisTemplate);
    }

    @Bean("redisTemplate")
    public RedisTemplate<String, V> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, V> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        //设置key的序列化方式
        template.setKeySerializer(RedisSerializer.string());
        //设置value的序列化方式
        template.setValueSerializer(RedisSerializer.json());
        //设置hash的key的序列化方式
        template.setHashKeySerializer(RedisSerializer.string());
        //设置hash的value的序列化方式
        template.setHashValueSerializer(RedisSerializer.json());
        return template;
    }

    /**
     * 创建连接redis的客户端对象【后续将消息发送给redis 再有redis分发其他设备，解决分布式服务和发现】
     */
    @Bean(name = "redissonClient", destroyMethod = "shutdown")
    public RedissonClient redissonClient() {
        try {
            Config config = new Config();
            config.useSingleServer().setAddress("redis://" + redisLocal + ":" + redisPort);
            return Redisson.create(config);
        } catch (Exception e) {
            log.error("----------初始化redis客户端失败----------\n", e);
        }
        return null;
    }

    @Bean
    public RedisComponent<V> redisComponent(RedisTool<V> redisTool) {
        return new RedisComponent<>(redisTool);
    }

    @Bean
    public JwtUtil<V> jwtUtil(RedisTool<V> redisTool) {
        return new JwtUtil<>(redisTool);
    }

    @Bean
    public SendUtils sendUtils() {
        return new SendUtils();
    }
}
